<template>
  <div>

    <el-row>
      <el-col :span="6" :offset="3">
        <p style="font-">内部吐槽群</p>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12" :offset="1">
        <div class="textarea" id="textarea"></div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="12" :offset="1">
        <el-input type="text" placeholder="请输入用户名" v-model="userName" />
        <el-button type="primary" @click="join">加入聊天室</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="5" :offset="1"> <el-input type="text" v-model="message" /> </el-col>
      <el-button type="primary" @click="send">发送</el-button>

      <el-button type="primary" @click="leave">离开聊天室</el-button>
    </el-row>

  </div>
</template>

<script>

export default {
  data() {
    return {
      url: 'ws://127.0.0.1:8092/WebSocketHandler/',
      ws: '',
      userName: '',
      message: ''
    }

  },
  methods: {
    join() {
      if (this.userName == "") {
        alert("请输入您的大名！")
      }
      // 关闭旧的连接（如果有的话）
      if (this.ws) {
        this.ws.close()
      }

      let _this = this; // 保存对this的引用
      this.ws = new WebSocket(this.url + this.userName);

      this.ws.onopen = function () {
        console.log("连接成功！")
      }
      this.ws.onmessage = function (result) {
        var textarea = document.getElementById("textarea");
        let beforeHtml = textarea.innerHTML;
        let msg = result.data.split(":");
        if (_this.userName == msg[0]) { // 使用保存的引用
          textarea.innerHTML = beforeHtml + "<span style=' background-color: #409EFF;  float:right; '>" + msg[1] + ':' + msg[0] + "</span>" + "</br>"
        } else {
          textarea.innerHTML = beforeHtml + '<span>' + result.data + '</span>' + '</br>'
        }
      }

      this.ws.onclose = function () {
        var textarea = document.getElementById("textarea");
        textarea.append('用户：' + _this.userName + '离开聊天室 \n'); // 使用保存的引用
        console.log("")
      }

    },
    send() {
      if (this.ws != null) {
        this.ws.send(this.message);
        this.message = "";
      }
    },
    leave() {
      if (this.ws != null) {
        this.ws.close();
        this.ws = null;

        // 如果需要重定向到其他页面，
      }
    }
  }
}
</script>

<style scoped>
p {
  font-size: 20px;
  color: red;
}

.el-row {
  margin: 10px 5px;
}

.textarea {
  width: 350px;
  height: 360px;
  border: 1px solid;
  overflow-y: auto
}

.el-input {
  width: 250px;
}


.container {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  color: #2c3e50;
  margin-top: 60px;
}

.title {
  text-align: center;
  font-weight: bold;
  color: #34495e;
  font-size: 36px;
  margin-bottom: 40px;
}

.chatlog {
  min-height: 300px;
  border: 1px solid #bdc3c7;
  border-radius: 2px;
  padding: 20px;
  margin-bottom: 20px;
  overflow: auto;
  background-color: #ecf0f1;
}

.el-input {
  margin-bottom: 20px;
}
</style>
